package com.pioneer.fationservice.fragments;

import java.io.File;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.pioneer.fationservice.R;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.entries.UsrInfoEntry;
import com.pioneer.fationservice.helpers.ConfigHelper;
import com.pioneer.fationservice.models.ResponseObject;
import com.pioneer.fationservice.models.UsrinfoModel;
import com.pioneer.fationservice.parsers.BaseParser;
import com.pioneer.fationservice.parsers.UsrinfoParser;
import com.pioneer.fationservice.serviceinfos.CollectionActivity;
import com.pioneer.fationservice.serviceinfos.LoginActivity;

/**
 * 个人中心页面
 * @author Mrper
 *
 */
public class FragmentUsrinfo extends Fragment implements android.view.View.OnClickListener{

	public static final String TAG = "FragmentUsrinfo";
	
	@ViewInject(id=R.id.layout_actionbar_txtTitle) private TextView txtTitle;//标题文本栏
	@ViewInject(id=R.id.fragment_usrinfo_imgEdit,click="onChangeUsrinfoClick") private ImageView imgEdit;//改变用户信息
	@ViewInject(id=R.id.fragment_usrinfo_imgHeader,click="onHeaderIconClick") private ImageView imgHeader;//用户头像
	@ViewInject(id=R.id.fragment_usrinfo_txtNickname) private TextView txtNickname;//用户昵称
	@ViewInject(id=R.id.fragment_usrinfo_txtCall) private TextView txtCall;//联系电话
	@ViewInject(id=R.id.fragment_usrinfo_txtScore) private TextView txtScore;//我的积分
	@ViewInject(id=R.id.fragment_usrinfo_txtEmail) private TextView txtEmail;//我的邮箱
	@ViewInject(id=R.id.fragment_usrinfo_txtRecorder,click="onItemClick") private TextView txtRecorder;//消费记录
	@ViewInject(id=R.id.fragment_usrinfo_txtCollect,click="onItemClick") private TextView txtCollect;//我的收藏
	@ViewInject(id=R.id.fragment_usrinfo_btnLogout,click="onLogoutClick") private Button btnLogout;//退出账户
	
	private PopupWindow winHeaderUpload;//头像上传窗口
	private static final int REQUEST_LOCAL_PIC = 0x0001;//请求本地图片
	private static final int REQUEST_TAKE_PHOTO = 0x0002;//请求拍照上传
	private File fileHeader = new File(SystemData.CACHE_DIR + "header.jpg");//用户头像
	private File fileHeaderCache = new File(SystemData.CACHE_DIR + "header_photo.jpg");//头像缓存图片
	
	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		View viewRoot = inflater.inflate(R.layout.fragment_usrinfo, null);
		FinalActivity.initInjectedView(this, viewRoot);
		return viewRoot;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		txtTitle.setText("个人中心");
		//如果头像文件夹不存在，则创建该文件夹
		File filePicParent = fileHeader.getParentFile();
		if(!filePicParent.exists()) filePicParent.mkdirs();
		initWinHeaderUpload();//初始化头像上传窗口
		requestUserHeaderIcon();//请求用户头像
		requestUserInfo();//请求用户信息
	}
	
	/**
	 * 初始化头像上传窗口
	 */
	public void initWinHeaderUpload(){
		View view = View.inflate(getActivity(), R.layout.win_user_upload_headicon, null);
		((TextView)view.findViewById(R.id.win_user_upload_headicon_txtCancel)).setOnClickListener(this);
		((TextView)view.findViewById(R.id.win_user_upload_headicon_txtLocUpload)).setOnClickListener(this);
		((TextView)view.findViewById(R.id.win_user_upload_headicon_txtTakePhotoUpload)).setOnClickListener(this);
		winHeaderUpload = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT, true);
		winHeaderUpload.setAnimationStyle(R.style.WinUploadHeaderIconStyle);
		winHeaderUpload.setOutsideTouchable(true);
		winHeaderUpload.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		winHeaderUpload.update();
	}
	
	/**
	 * 修改用户信息
	 * @param view
	 */
	public void onChangeUsrinfoClick(View view){
		
	}
	
	/**
	 * 头像点击事件
	 * @param view
	 */
	public void onHeaderIconClick(View view){
		if(winHeaderUpload!=null)
			winHeaderUpload.showAtLocation(view, Gravity.BOTTOM, 0,0);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.win_user_upload_headicon_txtCancel://取消上传
			hideWinHeaderUpload();//隐藏上传头像的窗口
			break;
		case R.id.win_user_upload_headicon_txtLocUpload://本地上传
			hideWinHeaderUpload();//隐藏上传头像的窗口
			cropPicAsHeaderIcon(MediaStore.Images.Media.INTERNAL_CONTENT_URI,Intent.ACTION_GET_CONTENT,fileHeader);
			break;
		case R.id.win_user_upload_headicon_txtTakePhotoUpload://拍照上传
			hideWinHeaderUpload();//隐藏上传头像的窗口
			takePicAsHeaderIcon();//调用相机照相
			break;
		}
	}
	
	/**
	 * 隐藏上传头像的窗口
	 */
	public void hideWinHeaderUpload(){
		if(winHeaderUpload!=null) 
			winHeaderUpload.dismiss();
	}
	
	/**
	 * 退出账户操作
	 * @param view
	 */
	public void onLogoutClick(View view){
		new AlertDialog.Builder(getActivity())
			.setTitle("温馨提示").setMessage("您确定要退出吗？退出账户后将会退出整个应用程序!")
			.setIcon(android.R.drawable.ic_menu_info_details).setNegativeButton("取消", null)
			.setPositiveButton("确定", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ConfigHelper.getInstance(getActivity()).getConfigEditor().putInt("uid", 0).commit();
					getActivity().finish();
				}
			})
		.show();
	}
	
	/**
	 * 操作项点击事件
	 * @param view
	 */
	public void onItemClick(View view){
		switch(view.getId()){
		case R.id.fragment_usrinfo_txtRecorder:
			Toast.makeText(getActivity(), "暂未开放此功能!", Toast.LENGTH_SHORT).show();
			break;
		case R.id.fragment_usrinfo_txtCollect:
			startActivity(new Intent(getActivity(),CollectionActivity.class));
			getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
			break;
		}
	}
	
	/**
	 * 裁剪本地图片作为头像
	 */
	public void cropPicAsHeaderIcon(Uri fromUri,String intentAction,File outfile){
		Intent intent = new Intent(intentAction);
		// this will open all images in the Galery
		intent.setDataAndType(fromUri, "image/*");
		intent.putExtra("crop", "true");
		// this defines the aspect ration
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// this defines the output bitmap size
		intent.putExtra("outputX", 120);
		intent.putExtra("outputY", 120);
		// true to return a Bitmap, false to directly save the cropped iamge
		intent.putExtra("return-data", false);
		//save output image in uri
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outfile));
		startActivityForResult(intent, REQUEST_LOCAL_PIC);
	}
	
	/**
	 * 拍照图片作为头像
	 */
	public void takePicAsHeaderIcon(){
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(fileHeaderCache));
		startActivityForResult(intent, REQUEST_TAKE_PHOTO);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
		case REQUEST_LOCAL_PIC:
			if(resultCode ==Activity.RESULT_OK && fileHeader.exists())//上传用户头像
				uploadUserHeaderIcon(fileHeader);
			break;
		case REQUEST_TAKE_PHOTO:
			if(Activity.RESULT_OK == resultCode && fileHeaderCache.exists()){
				txtNickname.postDelayed(new Runnable(){//对拍下来的照片进行截图处理
					@Override
					public void run() {
						cropPicAsHeaderIcon(Uri.fromFile(fileHeaderCache),
								"com.android.camera.action.CROP",fileHeader);
					}
				}, 500);
			}
		}
	}
	
	/**
	 * 设置用户信息
	 */
	public void setUsrInfo(UsrInfoEntry entry){
		if(entry == null) return;
		txtCall.setText(entry.usrPhone);
		txtNickname.setText(entry.usrName);
		txtScore.setText(String.valueOf(entry.usrScore));
		txtEmail.setText(Html.fromHtml("<font color='gray'>"+entry.usrEmail + "</font>"));
	}
	
	/**
	 * 请求用户信息
	 */
	public void requestUserInfo(){
		final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "正在获取用户信息...");
		AjaxParams params = new AjaxParams();
		params.put("uid", String.valueOf(SystemData.uid));
		new FinalHttp().post(SystemHttpURL.URL_USER_GET_INFO, params,new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				if(dialog!=null) dialog.dismiss();
				Toast.makeText(getActivity(), "获取用户信息失败，请检查网络!",Toast.LENGTH_SHORT).show();
			}
			@Override
			public void onSuccess(String str) {
				super.onSuccess(str);
				if(dialog!=null) dialog.dismiss();
				System.out.println("获取用户信息--结果返回："+str);
				UsrinfoModel model = new UsrinfoParser(str).getResponseObject();
				switch(model.status){
				case 1:
					setUsrInfo(model.usrinfo);//设置用户信息
					Toast.makeText(getActivity(), "获取用户信息成功！",Toast.LENGTH_SHORT).show();
					break;
				case 0:
					Toast.makeText(getActivity(), "获取用户信息失败！" + model.msg,Toast.LENGTH_SHORT).show();
					break;
				}
			}
		});
	}
	
	
	/**
	 * 上传用户头像
	 */
	public void uploadUserHeaderIcon(File fileHeader){
		try{
			final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "正在上传用户头像...");
			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();
			params.put("uid", String.valueOf(SystemData.uid));
			params.put("filehead", fileHeader);
			finalHttp.post(SystemHttpURL.URL_USER_UPLOAD_HEADER, params,new AjaxCallBack<String>() {
				@Override
				public void onFailure(Throwable t, int errorNo, String strMsg) {
					super.onFailure(t, errorNo, strMsg);
					if(dialog!=null) dialog.dismiss();
					Toast.makeText(getActivity(), "网络错误，头像上传失败!",Toast.LENGTH_SHORT).show();
				}
				@Override
				public void onSuccess(String str) {
					super.onSuccess(str);
					if(dialog!=null) dialog.dismiss();
					System.out.println("上传用户头像--结果返回："+str);
					ResponseObject model = (new BaseParser(ResponseObject.class,str){
						@Override
						public void parseJSONModels(Object jsonModels,boolean isJSONObject) {
						}
					}).getResponseObject();
					if(model.status == 1) requestUserHeaderIcon();//再次请求头像
					Toast.makeText(getActivity(), model.status == 1?"头像上传成功!":model.msg,
							Toast.LENGTH_SHORT).show();
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 请求用户头像
	 */
	public void requestUserHeaderIcon(){
		FinalBitmap.create(getActivity()).display(imgHeader, SystemHttpURL.URL_USER_GET_HEADER +"?uid="+SystemData.uid 
				+ "&rand=" + System.currentTimeMillis());
//		new FinalHttp().download(SystemHttpURL.URL_USER_GET_HEADER, params, fileHeader.getAbsolutePath(),
//			new AjaxCallBack<File>() {
//				@Override
//				public void onFailure(Throwable t, int errorNo, String strMsg) {
//					super.onFailure(t, errorNo, strMsg);
//					Toast.makeText(getActivity(), "获取头像失败！", Toast.LENGTH_SHORT).show();
//				}
//				@Override
//				public void onSuccess(File file) {
//					super.onSuccess(file);
//					if(fileHeader == null || !fileHeader.exists()) return;
//					Drawable drawable = Drawable.createFromPath(fileHeader.getAbsolutePath());
//					drawable.setBounds(0, 0	, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
//					imgHeader.setImageDrawable(drawable);
//				}
//			}
//		);
	}
	
	
}
